import {reqUserSubject} from '../../api'

//状态对象
const state = {
    subjectId: localStorage.getItem('subjectId') || '',
    subjectName: localStorage.getItem('subjectName') || '',
    firstTypeId: localStorage.getItem('firstTypeId') || '',
    secondTypeId: localStorage.getItem('secondTypeId') || '',
}

//基于state的getter计算属性的对象
const getters = {
    // Filtering currentUser
    currentSubject: state => {
        return {
            subjectId: state.subjectId,
            subjectName: state.subjectName,
            firstTypeId: state.firstTypeId,
            secondTypeId: state.secondTypeId
        }
    }
}

//更新state的多个方法的对象
const mutations = {
    getSubject(state) {
        state.subjectId = localStorage.getItem('subjectId');
        state.subjectName = localStorage.getItem('subjectName');
        state.firstTypeId = localStorage.getItem('firstTypeId');
        state.secondTypeId = localStorage.getItem('secondTypeId');
    },
    setSubject(state, payload) {
        localStorage.setItem('subjectId', payload.subjectId);
        localStorage.setItem('subjectName', payload.subjectName);
        localStorage.setItem('firstTypeId', payload.firstTypeId);
        localStorage.setItem('secondTypeId', payload.secondTypeId);
        state.subjectId = payload.subjectId;
        state.subjectName = payload.subjectName;
        state.firstTypeId = payload.firstTypeId;
        state.secondTypeId = payload.secondTypeId;
    },
    logout(state) {
        localStorage.removeItem('subjectId');
        localStorage.removeItem('subjectName');
        localStorage.removeItem('firstTypeId');
        localStorage.removeItem('secondTypeId');
        state.subjectId = '';
        state.subjectName = '';
        state.firstTypeId = '';
        state.secondTypeId = '';
    }
}

//通过mutations间接更新state的多个方法的对象
const actions = {
    //获取用户选择的科目
    async ['reqUserSubject'](store, config = {}) {
        const {commit, rootState} = store
        //发送异步ajax请求
        var parmas = {'userId': rootState.user.userId};
        const result = await reqUserSubject(parmas);
        //提交一个mutation
        if (result.code === 0) {
            const data = result.data;
            commit('setSubject', data);
        }
    },

    //同步记录用户所选科目
    setSubject({commit}, data) {
        commit('setSubject', data);
    }
}

export default {
    state,
    getters,
    mutations,
    actions
}
